#include "Driver.h"

Driver::Driver(wchar_t* _driverName, wchar_t* _driverExec)
{
	driverName = new wchar_t[wcslen(_driverName) + 1];
	wcscpy(driverName, _driverName);
	driverExec = new wchar_t[wcslen(_driverExec) + 1];
	wcscpy(driverExec, _driverExec);
}

Driver::~Driver()
{
	delete [] driverName;
	driverName = NULL;
	delete [] driverExec;
	driverExec = NULL;
}

BOOL Driver::Install()
{
	SC_HANDLE scm = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
	if (scm == NULL)
		return FALSE;
	
	SC_HANDLE Service = CreateService(scm, driverName, driverName, SERVICE_ALL_ACCESS, SERVICE_FILE_SYSTEM_DRIVER, 
									  SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, driverExec,           
									  NULL, NULL, NULL, NULL, NULL);
	
	if (Service == NULL) 
		return FALSE;
	
	CloseServiceHandle(Service);
	CloseServiceHandle(scm);

	return TRUE;
}

BOOL Driver::Remove()
{
	SC_HANDLE scm = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
	if (scm == NULL)
		return FALSE;

	SC_HANDLE Service = OpenService(scm, driverName, SERVICE_ALL_ACCESS);
	if (Service == NULL) 
		return FALSE;
	
	BOOL ret = DeleteService(Service);
	if (!ret) 
		return FALSE;

	CloseServiceHandle(Service);
	CloseServiceHandle(scm);

	return ret;
}

BOOL Driver::Start()
{
	SC_HANDLE scm = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
	if (scm == NULL)
		return FALSE;

	SC_HANDLE Service =	OpenService(scm, driverName, SERVICE_ALL_ACCESS);
	if (Service == NULL) 
		return FALSE;
	
	BOOL ret = StartService(Service, 0, NULL);
	if (!ret)
		return FALSE;
	
	CloseServiceHandle(Service);
	CloseServiceHandle(scm);

	return ret;
}

BOOL Driver::Stop()
{
	SC_HANDLE scm = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
	if (scm == NULL)
		return FALSE;

	SC_HANDLE Service = OpenService (scm, driverName, SERVICE_ALL_ACCESS);
	if (Service == NULL)  
		return FALSE;
	
	SERVICE_STATUS serviceStatus;
	BOOL ret = ControlService(Service, SERVICE_CONTROL_STOP, &serviceStatus);
	if (!ret)
		return FALSE;
	
	CloseServiceHandle(Service);
	CloseServiceHandle(scm);

	return ret;
}
